import { ref } from 'vue'
import type { SelectProps } from 'ant-design-vue'
import { Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'
import type { TableColumns } from '@/types/antd'
import { v4 } from 'uuid'
import Api from '@/libs/api'
import type { ApiResponse } from './types'
import { useI18n } from 'vue-i18n'

export const useGoodsFreightInfo = () => {
	const { t } = useI18n()
	const provinces = ref<SelectProps['options']>([])

	const getRemoteFrightColumns = () =>
		[
			{
				title: t('商品详细.省份'),
				dataIndex: 'provinceId',
				align: 'center' as const,
				key: 'provinceId'
			},
			{
				title: t('商品详细.追加运费'),
				dataIndex: 'appendFreightPrice',
				align: 'center' as const,
				key: 'appendFreightPrice'
			},
			{
				title: t('状态.操作'),
				dataIndex: 'action',
				align: 'center' as const,
				key: 'action'
			}
		] as TableColumns

	const provincesInit = () => {
		Api.post('/base-data/areas/province-select').then((res: ApiResponse) => {
			if (res.list) {
				provinces.value = res.list
			}
		})
	}

	const addRemoteFright = (remoteFreights: any[]) => {
		remoteFreights.unshift({
			id: 0,
			uuid: v4(),
			provinceId: '',
			appendFreightPrice: 0
		})
	}

	const delRemoteFreight = (uuid: string, remoteFreights: any[]) => {
		Modal.confirm({
			title: '确认删除?',
			icon: createVNode(ExclamationCircleOutlined),
			onOk() {
				remoteFreights.forEach((item, key) => {
					if (item.uuid === uuid) {
						remoteFreights.splice(key, 1)
					}
				})
			}
		})
	}

	return {
		provinces,
		getRemoteFrightColumns,
		provincesInit,
		addRemoteFright,
		delRemoteFreight
	}
}
